import pandas as pd
import uuid
import json
import time
import mysql.connector
import tos
import logging
from bytehouse_driver import Client
import numpy as np
def add_to_bytehouse(dict_list):

    print(dict_list)
    HOST="bytehouse-cn-beijing.volces.com"
    PORT="19000"
    API_KEY="q2p9nLj7tq:TKOCmgrMKp"
    # 配置数据库连接信息
    DATABASE="dwd"
    client = Client.from_url('bytehouse://{}:{}/?user=bytehouse&password={}&database={}&secure=true'.format(HOST, PORT, API_KEY, DATABASE))
    client.execute("INSERT INTO dwd.dwd_trigger_sc_ep40_tda4_v5 VALUES", dict_list)
def get_dict_list(dict):
    data_list=[]
    data_list.append(dict['vehicle_id'])
    data_list.append(dict['start_time_str'])
    data_list.append(dict['scid'])
    data_list.append(dict['path'])
    data_list.append(dict['level1'])
    data_list.append(dict['level2'])
    data_list.append(dict['level3'])
    data_list.append(dict['day'])
    data_list.append(dict['month'])
    data_list.append(dict["scid_start_time_str"])
    data_list.append(dict['icu2_odometer'])
    data_list.append(dict['idb3_vehiclespd'])
    data_list.append(dict['acu2_longaccsensorvalue'])
    data_list.append(dict['acu2_lataccsensorvalue'])
    data_list.append(dict['acu2_vehicledynyawrate'])
    data_list.append(dict['eps1_steeranglespd'])
    data_list.append(dict['lane_curvature'])
    data_list.append(dict['eps1_torsionbartorque'])
    data_list.append(dict['cs1_gearpositionreqst'])
    data_list.append(dict['uid'])
    data_list.append(dict['day'])
    return data_list
def get_dict(vechicle_id,start_time_str,bagid,path,scid_dict,level1,level2,level3):
    dict = {}
    dict["vehicle_id"] = vechicle_id
    dict["start_time_str"] = start_time_str
    dict["scid"] = bagid
    dict["path"] = path
    dict["level1"] = level1
    dict["level2"] = level2
    dict["level3"] = level3
    day = start_time_str[0:4] + start_time_str[5:7] + start_time_str[8:10]
    month = start_time_str[0:4] + start_time_str[5:7]
    dict["day"] = day
    dict["month"] = month
    dict["scid_start_time_str"] = scid_dict["scid_start_time_str"]
    dict["icu2_odometer"] = scid_dict["ICU2_Odometer"]
    dict["idb3_vehiclespd"] = scid_dict["IDB3_VehicleSpd"]
    dict["acu2_longaccsensorvalue"] = scid_dict["ACU2_LongAccSensorValue"]
    dict["acu2_lataccsensorvalue"] = scid_dict["ACU2_LatAccSensorValue"]
    dict["acu2_vehicledynyawrate"] = scid_dict["ACU2_VehicleDynYawRate"]
    dict["eps1_steeranglespd"] = scid_dict["EPS1_SteerAngleSpd"]
    dict["lane_curvature"] = scid_dict["lane_curvature"]
    dict["eps1_torsionbartorque"] = scid_dict["EPS1_TorsionBarTorque"]
    dict["cs1_gearpositionreqst"] = scid_dict["CS1_GearPositionReqSt"]
    dict["lane_curvature"] = scid_dict["lane_curvature"]

    uid_string = vechicle_id + start_time_str + bagid + level1 + level2 + level3
    uid = str(uuid.uuid3(uuid.NAMESPACE_DNS, uid_string))
    dict["uid"] = uid
    return dict
def get_scid_time(df_no_expect_take_over_100ms):
    df_no_expect_take_over_100ms_list = df_no_expect_take_over_100ms[
        ['start_time_str', 'path', 'nsecs', 'VLCCDHypotheses_Hypothesis_0_fTTC', 'VLCCDHypotheses_Hypothesis_0_fDistX',
         'VLCCDHypotheses_Hypothesis_0_fDistY',
         'VLCCDHypotheses_Hypothesis_0_fVrelX', 'VLCCDHypotheses_Hypothesis_0_fVrelY', 'IDB3_VehicleSpd',
         'ACU2_LongAccSensorValue', 'ACU2_LatAccSensorValue',
         'ACU2_VehicleDynYawRate', 'IDB1_BrakePedalApplied', 'EPS1_SteerAngleSpd',
         'CamLaneData_CourseInfo_1_CourseInfoSegNear_f_C0',
         'ADCS8_FCWStatus','ICU2_Odometer','EPS1_TorsionBarTorque','CS1_GearPositionReqSt','ADCS8_NPilot_SysState',
         'ADCS8_NNPSysState','IDB1_BrakePedalApplied'
         ]].values.tolist()
    found_index = -9999
    start_time_str=""
    found_ICU2_Odometer=0.0
    found_IDB3_VehicleSpd=0.0
    found_ACU2_LongAccSensorValue=0.0
    found_ACU2_LatAccSensorValue=0.0
    found_ACU2_VehicleDynYawRate=0.0
    found_EPS1_SteerAngleSpd=0.0
    found_EPS1_TorsionBarTorque=0.0
    found_CS1_GearPositionReqSt=0
    found_lane_curvature=0.0
    # 遍历列表

    for index, element in enumerate(df_no_expect_take_over_100ms_list):
        start_time_str=element[0]
        path = element[1]
        nsecs = element[2]
        ICU2_Odometer = element[16]
        IDB3_VehicleSpd = element[8]
        ACU2_LongAccSensorValue = element[9]
        ACU2_LatAccSensorValue = element[10]
        ACU2_VehicleDynYawRate = element[11]
        EPS1_SteerAngleSpd = element[13]
        lane_curvature= element[14]
        EPS1_TorsionBarTorque= element[17]
        CS1_GearPositionReqSt = element[18]
        ADCS8_NPilot_SysState= element[19]
        ADCS8_NNPSysState= element[20]
        IDB1_BrakePedalApplied= element[21]
        if (ADCS8_NPilot_SysState==2 or ADCS8_NNPSysState==2) and (IDB1_BrakePedalApplied==1 or EPS1_TorsionBarTorque>3):
            found_index = index
            found_ICU2_Odometer = ICU2_Odometer
            found_IDB3_VehicleSpd = IDB3_VehicleSpd
            found_ACU2_LongAccSensorValue = ACU2_LongAccSensorValue
            found_ACU2_LatAccSensorValue =ACU2_LatAccSensorValue
            found_ACU2_VehicleDynYawRate = ACU2_VehicleDynYawRate
            found_EPS1_SteerAngleSpd =EPS1_SteerAngleSpd
            found_lane_curvature=lane_curvature
            found_EPS1_TorsionBarTorque = EPS1_TorsionBarTorque
            found_CS1_GearPositionReqSt =CS1_GearPositionReqSt
            break  # 找到第一个符合条件的元素就跳出循环
    logging.info("found_index: "+str(found_index))
    dict_scid={}
    dict_scid["scid_start_time_str"]=start_time_str
    dict_scid["ICU2_Odometer"] = found_ICU2_Odometer
    dict_scid["IDB3_VehicleSpd"] = found_IDB3_VehicleSpd
    dict_scid["ACU2_LongAccSensorValue"] = found_ACU2_LongAccSensorValue
    dict_scid["ACU2_LatAccSensorValue"] = found_ACU2_LatAccSensorValue
    dict_scid["ACU2_VehicleDynYawRate"] = found_ACU2_VehicleDynYawRate
    dict_scid["EPS1_SteerAngleSpd"] = found_EPS1_SteerAngleSpd
    dict_scid["lane_curvature"] = found_lane_curvature
    dict_scid["EPS1_TorsionBarTorque"] = found_EPS1_TorsionBarTorque
    dict_scid["CS1_GearPositionReqSt"] = found_CS1_GearPositionReqSt
    return dict_scid
def get_no_expect_take_over_can_100ms(df_can_100ms_save_path, vechicle_id, daystr, hourstr, bagid, uuids, file_type):
    try:
        df_can_100ms_no_expect_take_over= pd.read_pickle(df_can_100ms_save_path)
    except Exception as e:
        print('data report read error, ', str(e))

    df_can_100ms_no_expect_take_over_list = df_can_100ms_no_expect_take_over[
        ['start_time_str', 'path','nsecs','ADCS8_NPilot_SysState','ADCS8_NNPSysState','IDB1_BrakePedalApplied',
         'EPS1_TorsionBarTorque']].values.tolist()
    scid_dict = get_scid_time(df_can_100ms_no_expect_take_over)
    dict_list=[]
    ADCS8_NPilot_SysState_last=df_can_100ms_no_expect_take_over_list[0][3]
    ADCS8_NNPSysState_last=df_can_100ms_no_expect_take_over_list[0][4]
    IDB1_BrakePedalApplied_last=df_can_100ms_no_expect_take_over_list[0][5]
    EPS1_TorsionBarTorque_last = df_can_100ms_no_expect_take_over_list[0][6]
    for index, row in enumerate(df_can_100ms_no_expect_take_over_list):
        start_time_str=row[0]
        path=row[1]
        nsecs=row[2]
        ADCS8_NPilot_SysState=row[3]
        ADCS8_NNPSysState=row[4]
        IDB1_BrakePedalApplied=row[5]
        EPS1_TorsionBarTorque=row[6]

        if index-1>=0 and index+1<=len(df_can_100ms_no_expect_take_over_list)-1:
            ADCS8_NNPSysState_last1=df_can_100ms_no_expect_take_over_list[index-1][4]
            ADCS8_NNPSysState_next1= df_can_100ms_no_expect_take_over_list[index+1][4]
            if (ADCS8_NPilot_SysState == 2) and \
                (ADCS8_NNPSysState_last1!=2 and ADCS8_NNPSysState_next1!=2) and \
                ((IDB1_BrakePedalApplied_last==1 and IDB1_BrakePedalApplied!=1) or \
                 (EPS1_TorsionBarTorque_last<=3 and EPS1_TorsionBarTorque>3)):
                level1 = "非预期主动接管"
                level2 = "接管功能"
                level3 = "PILOT非预期主动接管"
                dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
                data_list = get_dict_list(dict)
                dict_list.append(data_list)

        if (ADCS8_NNPSysState_last==2 and ADCS8_NNPSysState!=2) and \
            (IDB1_BrakePedalApplied==1 or EPS1_TorsionBarTorque>3):
            level1 = "非预期主动接管"
            level2 = "接管功能"
            level3 = "NNP非预期主动接管"
            dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
            data_list = get_dict_list(dict)
            dict_list.append(data_list)

        if ( ADCS8_NPilot_SysState==2 or ADCS8_NNPSysState==2) and (IDB1_BrakePedalApplied_last!=1 and IDB1_BrakePedalApplied==1):
            level1 = "非预期主动接管"
            level2 = "接管功能"
            level3 = "刹车接管"
            dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
            data_list = get_dict_list(dict)
            dict_list.append(data_list)
        if (ADCS8_NPilot_SysState==2 or ADCS8_NNPSysState==2) and (EPS1_TorsionBarTorque_last<=3 and EPS1_TorsionBarTorque>3):
            level1 = "非预期主动接管"
            level2 = "接管功能"
            level3 = "方向盘接管"
            dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
            data_list = get_dict_list(dict)
            dict_list.append(data_list)

        if (ADCS8_NNPSysState_last==2 and ADCS8_NNPSysState not in[2,4]) and \
           (IDB1_BrakePedalApplied==1 or EPS1_TorsionBarTorque>3):
            level1 = "非预期主动接管"
            level2 = "接管功能"
            level3 = "NNP退出"
            dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
            data_list = get_dict_list(dict)
            dict_list.append(data_list)
        if index - 1 >= 0 and index + 1 <= len(df_can_100ms_no_expect_take_over_list) - 1:
            ADCS8_NNPSysState_last1=df_can_100ms_no_expect_take_over_list[index-1][4]
            ADCS8_NNPSysState_next1= df_can_100ms_no_expect_take_over_list[index+1][4]
            if (ADCS8_NPilot_SysState_last==2 and ADCS8_NPilot_SysState not in[2,3]) and \
                (ADCS8_NNPSysState_last1!=2 and ADCS8_NNPSysState_next1!=2)  and \
                (IDB1_BrakePedalApplied==1 or EPS1_TorsionBarTorque>3):
                level1 = "非预期主动接管"
                level2 = "接管功能"
                level3 = "PILOT退出"
                dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
                data_list = get_dict_list(dict)
                dict_list.append(data_list)
        if (ADCS8_NNPSysState_last==2 and ADCS8_NNPSysState==4) and \
            (IDB1_BrakePedalApplied==1 or EPS1_TorsionBarTorque>3):
            level1 = "非预期主动接管"
            level2 = "接管功能"
            level3 = "NNP suspend"
            dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
            data_list = get_dict_list(dict)
            dict_list.append(data_list)
        if index - 1 >= 0 and index + 1 <= len(df_can_100ms_no_expect_take_over_list) - 1:
            ADCS8_NNPSysState_last1=df_can_100ms_no_expect_take_over_list[index-1][4]
            ADCS8_NNPSysState_next1= df_can_100ms_no_expect_take_over_list[index+1][4]
            if (ADCS8_NPilot_SysState_last==2 and ADCS8_NPilot_SysState==3) and \
               (ADCS8_NNPSysState_last1!=2 and ADCS8_NNPSysState_next1!=2) and \
               (IDB1_BrakePedalApplied==1 or EPS1_TorsionBarTorque>3):
                level1 = "非预期主动接管"
                level2 = "接管功能"
                level3 = "PILOT suspend"
                dict = get_dict(vechicle_id, start_time_str, bagid, path, scid_dict, level1, level2, level3)
                data_list = get_dict_list(dict)
                dict_list.append(data_list)




        ADCS8_NPilot_SysState_last=ADCS8_NPilot_SysState
        ADCS8_NNPSysState_last=ADCS8_NNPSysState
        IDB1_BrakePedalApplied_last=IDB1_BrakePedalApplied
    add_to_bytehouse(dict_list)



